package com.jn.servicedemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class MessengerService extends Service {
    // 1. 创建Handler处理客户端消息
    private static class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: // 消息类型1：处理文本消息
                    String data = msg.getData().getString("content");
                    Log.d("asdf", "收到客户端消息：" + data);
                    break;
                case 2: // 消息类型2：处理数字
                    int value = msg.arg1;
                    Log.d("asdf", "收到数字：" + value);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    // 2. 通过Handler创建Messenger
    private final Messenger mMessenger = new Messenger(new IncomingHandler());

    // 3. 绑定服务时返回Messenger的Binder
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
}
